"""
Created on 2022-05-26
@author:刘飞
@description:用户模块路由
"""
import json
from datetime import timedelta
from fastapi import Depends, status, HTTPException
from fastapi import APIRouter
from fastapi.security import OAuth2PasswordRequestForm
from fastapi import Form
# from fastapi_pagination import Page
from fastapi_pagination.ext.sqlalchemy import paginate
from sqlalchemy.orm import Session
from apps.user import schemas
from apps.user import crud
from apps.user.dependencies import get_current_user, get_current_active_user, get_db
from utils.custom_config import ACCESS_TOKEN_EXPIRE_MINUTES
from utils.custom_response import util_response
from utils.custom_pagination import Page
from utils.util import obj_to_dict

router = APIRouter(
    prefix="/api/user",
    tags=["用户模块"])


@router.post('/register', summary='注册', response_model=schemas.BaseOut)
def register(username: str = Form(..., description='用户名'), password: str = Form(..., description='密码'),
             db: Session = Depends(get_db)):
    if crud.get_user(db, username):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='当前用户名已注册')
    crud.create_user(db, data={'username': username, 'password': password})
    return util_response()


@router.post("/login", response_model=schemas.TokenOut, summary='登录')
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = crud.authenticate_user(db, form_data.username, form_data.password)
    if not user:
        return util_response(err=status.HTTP_400_BAD_REQUEST, msg='用户名/密码错误！')
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = crud.create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    data = {"access_token": access_token, "token_type": "bearer"}
    # return util_response(data=data)
    return data


@router.get("/info", response_model=schemas.InfoOut, response_model_exclude={'password'}, summary='获取用户信息')
async def read_users_me(current_user: schemas.UserInfo = Depends(get_current_active_user)):
    data = {
        "id": current_user.id,
        "username": current_user.username,
        "email": current_user.email,
        "is_active": current_user.is_active,
    }
    return util_response(data=data)


@router.post('/list', response_model=schemas.BaseOut, summary='创建用户')
async def user_create(item: schemas.UserIn,
                      db: Session = Depends(get_db), ):
    if crud.get_user(db, item.username):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='用户名已存在')
    crud.create_user(db, item.dict())
    return util_response()


@router.get('/list', response_model=Page[schemas.UserInfo], summary='用户列表')
async def user_list(db: Session = Depends(get_db)
                    ):
    users = crud.get_user_list(db, {})
    data = {
        "total": paginate(users).total,
        "list": [i.dict() for i in paginate(users).items]
    }
    return util_response(data=data)


@router.get('/list/{pk}', response_model=schemas.InfoOut, summary='用户详情')
async def user_detail(pk,
                      db: Session = Depends(get_db)):
    user_obj = crud.get_user_id(db=db, pk=pk)
    if user_obj:
        return util_response(obj_to_dict(user_obj))
    else:
        return util_response(err=status.HTTP_400_BAD_REQUEST, data='查无此人')


@router.put('/list/{pk}', response_model=schemas.BaseOut, summary='编辑用户')
async def user_edit(pk,
                    item: schemas.BaseUser,  # 编辑用户不应包含密码
                    db: Session = Depends(get_db)
                    ):
    print(item)
    crud.user_edit(db=db, pk=pk, item=item.dict())
    return util_response()


@router.delete('/list/{pk}', response_model=schemas.BaseOut, summary='删除用户')
async def user_delete(pk,
                      db: Session = Depends(get_db)):
    crud.user_delete(db=db, pk=pk)
    return util_response()
